package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class ReportServicelmpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        List<LocalDate> localDateList = DateListUtils2(begin, end);
        String dateList = DateListUtils1(localDateList);
        turnoverReportVO.setDateList(dateList);
        List<BigDecimal> AmountList = new ArrayList<>();
        //将传入的开始和结束时间转换成LocalDateTime
        for (int i = 0; i < localDateList.size(); i++) {
            //遍历拿到每一天的时间
            LocalDateTime beginTime = LocalDateTime.of(localDateList.get(i), LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDateList.get(i), LocalTime.MAX);
            Integer status = Orders.COMPLETED;
            BigDecimal SumAmount = orderMapper.getSumAmount(beginTime, endTime, status);
            SumAmount = SumAmount == null ? BigDecimal.valueOf(0.0) : SumAmount;
            AmountList.add(SumAmount);
        }
        //拼接字符串
        String turnoverList = DateListUtils1(AmountList);
        turnoverReportVO.setTurnoverList(turnoverList);
        return turnoverReportVO;
    }


    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(DateListUtils1(DateListUtils2(begin, end)));
        List<LocalDate> localDateList = DateListUtils2(begin, end);
        List<Long> totalUserList = new ArrayList<>();
        List<Long> newUserList = new ArrayList<>();
        for (int i = 0; i < localDateList.size(); i++) {
            LocalDateTime beginTime = LocalDateTime.of(localDateList.get(i), LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDateList.get(i), LocalTime.MAX);
            Long SumUser = orderMapper.SumUser(endTime);//总量
            Long CountUser = orderMapper.CountUser(beginTime, endTime);//新增
            totalUserList.add(SumUser);
            newUserList.add(CountUser);
        }
        userReportVO.setTotalUserList(DateListUtils1(totalUserList));
        userReportVO.setNewUserList(DateListUtils1(newUserList));
        return userReportVO;
    }


    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO OrderReport(LocalDate begin, LocalDate end) {
        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(DateListUtils1(DateListUtils2(begin, end)));
        List<LocalDate> localDateList = DateListUtils2(begin, end);
        List<Long> CountOrdersList = new ArrayList<>();
        List<Long> CountYesOrdersList = new ArrayList<>();
        for (int i = 0; i < localDateList.size(); i++) {
            LocalDateTime beginTime = LocalDateTime.of(localDateList.get(i), LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDateList.get(i), LocalTime.MAX);
            Long countOrders = orderMapper.GetOrderCount(beginTime, endTime);//每日订单数
            Long countYesOrders = orderMapper.GetYesOrders(beginTime, endTime);//每日有效订单数
            CountOrdersList.add(countOrders);
            CountYesOrdersList.add(countYesOrders);
        }
        orderReportVO.setOrderCountList(DateListUtils1(CountOrdersList));
        orderReportVO.setValidOrderCountList(DateListUtils1(CountYesOrdersList));
        Integer totalOrderCount = orderMapper.gettotal();//订单总数
        Integer validOrderCount = orderMapper.getValidOrder();//有效订单数
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        Double orderCompletionRate = (validOrderCount / 1.0) / totalOrderCount;
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        return orderReportVO;
    }


    /**
     * 销量排行top10
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        List<GoodsSalesDTO> goodsSalesDTO = new ArrayList<>();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        goodsSalesDTO = orderMapper.top(beginTime, endTime);
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        for (int i = 0; i < goodsSalesDTO.size(); i++) {
            nameList.add(goodsSalesDTO.get(i).getName());
            numberList.add(String.valueOf(goodsSalesDTO.get(i).getNumber()));
        }
        salesTop10ReportVO.setNameList(DateListUtils1(nameList));
        salesTop10ReportVO.setNumberList(DateListUtils1(numberList));
        return salesTop10ReportVO;
    }

    public String GetExcel() throws IOException {
        String path = "C:\\Users\\Lenovo\\Desktop\\运营数据报表" + System.currentTimeMillis() + ".xlsx";

        // 创建工作簿
        try (XSSFWorkbook workbook = new XSSFWorkbook();
             FileOutputStream fileOut = new FileOutputStream(new File(path))) {

            // 创建工作表
            Sheet sheet = workbook.createSheet("Sheet1");

            // 创建单元格样式
            CellStyle headerStyle = workbook.createCellStyle();
            CellStyle centeredStyle = workbook.createCellStyle();
            CellStyle yellowBackgroundStyle = workbook.createCellStyle();
            CellStyle lightBlueBackgroundStyle = workbook.createCellStyle();

            // 设置加粗字体
            XSSFFont boldFont = (XSSFFont) workbook.createFont();
            boldFont.setBold(true);

            // 设置居中对齐
            centeredStyle.setAlignment(HorizontalAlignment.CENTER);
            centeredStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 设置背景色
            lightBlueBackgroundStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
            lightBlueBackgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            yellowBackgroundStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            yellowBackgroundStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            // 应用加粗字体和背景色
            headerStyle.setFont(boldFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);
            headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            // 创建行
            Row row1 = sheet.createRow(0);
            Row row2 = sheet.createRow(1);
            Row row3 = sheet.createRow(2);
            Row row4 = sheet.createRow(3);
            Row row5 = sheet.createRow(4);
            Row row6 = sheet.createRow(5);
            Row row7 = sheet.createRow(6);
            Row row8 = sheet.createRow(7);

            // 设置行高
            row1.setHeight((short) 500); // 设置第一行高度
            row2.setHeight((short) 500); // 设置第二行高度
            row3.setHeight((short) 400); // 设置第三行高度
            row4.setHeight((short) 400); // 设置第四行高度
            row5.setHeight((short) 300); // 设置第五行高度
            row6.setHeight((short) 300); // 设置第六行高度
            row7.setHeight((short) 300); // 设置第七行高度
            row8.setHeight((short) 300); // 设置第八行高度

            // 创建和设置单元格
            Cell cell1 = row1.createCell(0);
            cell1.setCellValue("运营数据报表");
            cell1.setCellStyle(headerStyle);

            Cell cell2 = row2.createCell(0);
            cell2.setCellStyle(headerStyle);

            // 合并第一行和第二行的单元格
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 5));

            // 设置实际内容的背景色
            Cell cell3 = row4.createCell(0);
            cell3.setCellValue("概览数据");
            cell3.setCellStyle(centeredStyle);
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 5));

            Cell cell7 = row7.createCell(0);
            cell7.setCellValue("明细数据");
            cell7.setCellStyle(centeredStyle);
            sheet.addMergedRegion(new CellRangeAddress(6, 6, 0, 5));

            // 在第五行添加标题
            Cell cell5_1 = row5.createCell(0);
            cell5_1.setCellValue("营业额");
            cell5_1.setCellStyle(centeredStyle);

            Cell cell5_2 = row5.createCell(2);
            cell5_2.setCellValue("订单完成率");
            cell5_2.setCellStyle(centeredStyle);

            Cell cell5_3 = row5.createCell(4);
            cell5_3.setCellValue("新增用户数");
            cell5_3.setCellStyle(centeredStyle);

            // 在第六行添加数据
            Cell cell6_1 = row6.createCell(0);
            cell6_1.setCellValue("有效订单");
            cell6_1.setCellStyle(centeredStyle);

            Cell cell6_2 = row6.createCell(2);
            cell6_2.setCellValue("平均客单价");
            cell6_2.setCellStyle(centeredStyle);

            // 在第八行添加标题
            Cell cell8_1 = row8.createCell(0);
            cell8_1.setCellValue("日期");
            cell8_1.setCellStyle(centeredStyle);

            Cell cell8_2 = row8.createCell(1);
            cell8_2.setCellValue("营业额");
            cell8_2.setCellStyle(centeredStyle);

            Cell cell8_3 = row8.createCell(2);
            cell8_3.setCellValue("有效订单");
            cell8_3.setCellStyle(centeredStyle);

            Cell cell8_4 = row8.createCell(3);
            cell8_4.setCellValue("订单完成率");
            cell8_4.setCellStyle(centeredStyle);

            Cell cell8_5 = row8.createCell(4);
            cell8_5.setCellValue("平均客单价");
            cell8_5.setCellStyle(centeredStyle);

            Cell cell8_6 = row8.createCell(5);
            cell8_6.setCellValue("新增用户数");
            cell8_6.setCellStyle(centeredStyle);

            // 设置所有列的宽度相同
            int columnWidth = 8000; // 设置合适的宽度值
            for (int i = 0; i < 6; i++) {
                sheet.setColumnWidth(i, columnWidth);
            }

            LocalDateTime begins = LocalDateTime.of(LocalDate.now().minusDays(30), LocalTime.MIN);
            LocalDateTime ends = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
            //写入数据
            BigDecimal turnovers = orderMapper.getSumAmount(begins, ends, Orders.COMPLETED);
            row5.createCell(1).setCellValue(String.valueOf(turnovers));//总营业额

            //订单完成率
            Long countOrder = orderMapper.GetOrderCount(begins, ends);//订单总数
            Long countYesOrder = orderMapper.GetYesOrders(begins, ends);//有效订单
            Double orderCompletionRates = 0.0;
            if (countOrder > 0) {
                orderCompletionRates = (countYesOrder / 1.0) / countOrder;
                row5.createCell(3).setCellValue(orderCompletionRates * 100 + "%");//订单完成率
            }

            Integer newUser = Math.toIntExact(orderMapper.CountUser(begins, ends));
            row5.createCell(5).setCellValue(newUser);//新增用户数量


            row6.createCell(1).setCellValue(countYesOrder);//有效订单

            BigDecimal unitPrices = BigDecimal.valueOf(0.0);
            if (countOrder > 0) {

                unitPrices = turnovers.divide(new BigDecimal(countOrder), 2, RoundingMode.HALF_UP);
            }
            row6.createCell(3).setCellValue(String.valueOf(unitPrices));//平均客单价


            for (int i = 0; i < 30; i++) {
                Row row = sheet.createRow(i + 8);//创建行9
                LocalDate date = LocalDate.now().minusDays(i);
                row.createCell(0).setCellValue(String.valueOf(date));//日期

                //获取该天时间区间
                LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
                LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);

                //营业额
                BigDecimal turnover = orderMapper.getSumAmount(begin, end, Orders.COMPLETED);
                turnover = turnover == null ? BigDecimal.valueOf(0.0) : turnover;
                row.createCell(1).setCellValue(String.valueOf(turnover));
                //每日有效订单数
                Long countYesOrders = orderMapper.GetYesOrders(begin, end);
                row.createCell(2).setCellValue(countYesOrders);

                //订单完成率
                Long countOrders = orderMapper.GetOrderCount(begin, end);//每日订单总数
                Double orderCompletionRate = 0.0;
                if (countOrders > 0) {
                    orderCompletionRate = (countYesOrders / 1.0) / countOrders;
                    row.createCell(3).setCellValue(orderCompletionRate * 100 + "%");
                }


                BigDecimal unitPrice = BigDecimal.valueOf(0.0);
                if (countOrders > 0) {
                    unitPrice = turnover.divide(new BigDecimal(countOrders), 2, RoundingMode.HALF_UP);
                }
                row.createCell(4).setCellValue(String.valueOf(unitPrice));//平均客单价

                //新增用户数
                Integer newUsers = Math.toIntExact(orderMapper.CountUser(begin, end));
                row.createCell(5).setCellValue(newUsers);//新增用户数
            }
            // 写入文件
            workbook.write(fileOut);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(String.valueOf(businessDataVO.getTurnover()));
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(String.valueOf(businessDataVO.getUnitPrice()));

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(String.valueOf(businessData.getTurnover()));
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(String.valueOf(businessData.getUnitPrice()));
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 拼接字符串
     *
     * @param begin
     * @param end
     * @return
     */
    public String DateListUtils1(List list) {
        //遍历集合拼接成规定字符串[?,?,?....]
        String ReturnList = "";
        for (int i = 0; i < list.size(); i++) {
            if (i != list.size() - 1) {
                ReturnList = ReturnList + list.get(i) + ",";
            } else {
                ReturnList = ReturnList + list.get(i);
            }
        }
        return ReturnList;
    }


    /**
     * 传入开始结束时间返回每一天的时间集合
     *
     * @return
     */
    public List<LocalDate> DateListUtils2(LocalDate begin, LocalDate end) {
        //将传入日期每一天存入集合
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        return localDateList;
    }

}
